package com.wyp168.leetcode;

public class StringAtoi {
    public static void main(String[] args) {
        int result = myAtoi("");
        System.out.println(result);
    }

    public static int myAtoi(String s) {
        char[] sc = s.toCharArray();
        int index = 0;
        int flag = 1;
        //去空格
        while(index < sc.length && sc[index] == ' ') {
            index ++;
        }
        //判断去掉空格后是否为空串
        if (index == sc.length)
            return 0;
        //判断正负
        if (sc[index] == '+' || sc[index] == '-') {
            if (sc[index] == '-')
                flag = -1;
            index ++;
        }

        int res = 0;

        for (int i = index; i < sc.length; i++) {
            int number = sc[i] - 48;
            if (number >= 0 && number <= 9) {
                int temp = res * 10 + number;

                //判断是否越界，越界之后，和原来的值不一样
                if(temp / 10 != res) {  //越界
                    if (flag == 1) {
                        return Integer.MAX_VALUE;
                    } else {
                        return Integer.MIN_VALUE;
                    }
                }
                res = res * 10 + number;


            } else {
                break;
            }
        }

        return flag * res;


    }

}
